package com.ttl.web.controller;

import cn.hutool.core.codec.Base64Encoder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.ttl.web.entity.LoginUser;
import com.ttl.web.entity.PageParam;
import com.ttl.web.entity.SysUser;
import com.ttl.web.entity.SysUserPassword;
import com.ttl.web.service.SysUserService;
import jakarta.annotation.Resource;

import javax.imageio.ImageIO;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import com.ttl.web.utils.ResultVo;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Optional;

/**
 * 系统用户(管理员)
 * @author 上玄
 * @since 2024/8/01 16:30
 **/

@RestController
@RequestMapping("/api/sysUser")
public class SysUserController {
    @Resource
    private SysUserService sysUserService;
    @Resource
    private DefaultKaptcha defaultKaptcha;

    // 获取验证码
    @PostMapping("/captcha")
    public ResultVo imageCode(HttpServletRequest request) {
        //生成的验证码
        String code = defaultKaptcha.createText();
        // 验证码存入session
        HttpSession session = request.getSession();
        session.setAttribute("code", code);
//        System.out.println(session);
        System.out.println(session.getAttribute("code"));
        //生成图片,转换为bas64字符串
        BufferedImage bufferedImage = defaultKaptcha.createImage(code);
        ByteArrayOutputStream outputStream = null;
        try {
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", outputStream);
            Base64Encoder encoder = new Base64Encoder();
            String base64 = encoder.encode(outputStream.toByteArray());
            String codeImage = "data:image/jpg;base64," + base64.replaceAll("\r\n", "");
            return ResultVo.success("获取成功",codeImage);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return ResultVo.success("获取成功",code);
    }


    //注册
    @PostMapping("/register")
    public ResultVo register(@RequestBody SysUser user) {
        //判断用户名是否存在
        if (sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, user.getUsername())) != null) {
            return ResultVo.error("用户名已存在");
        }
        //判断手机号是否存在
        if (sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getPhone, user.getPhone())) != null) {
            return ResultVo.error("手机号已存在");
        }
        //密码hashMD5加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        //保存用户
        if (sysUserService.save(user)) {
            return ResultVo.success("注册成功");
        }else {
            return ResultVo.error("注册失败");
        }
    }


    //登录
    @PostMapping("/login")
    public ResultVo login(@RequestBody LoginUser loginUser, HttpServletRequest request) {
        //获取验证码
        String code = (String) request.getSession().getAttribute("code");
//        System.out.println(code);
        if (!StringUtils.equals(loginUser.getCaptcha(), code)) {
            return ResultVo.error("验证码错误");
        }
        SysUser user = new SysUser();
        user.setUsername(loginUser.getUsername());
        user.setPassword(loginUser.getPassword());
        //判断用户名是否存在
        SysUser u = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, user.getUsername()));
        if (u == null) {
            return ResultVo.error("用户不存在");
        }
        //密码hashMD5加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        //判断密码是否正确
        if (!u.getPassword().equals(user.getPassword())) {
            return ResultVo.error("密码错误");
        }
        //判断是否被停用
        if (u.getStatus().equals("1")) {
            return ResultVo.error("账号已被停用,请联系管理员");
        }
        //返回结果
        return ResultVo.success("登录成功",u);
    }

    // 修改密码
    @PostMapping("/changePassword")
    public ResultVo changePassword(@RequestBody SysUserPassword user) {
        // 更新密码：对新密码进行MD5加密，并更新到数据库中
        String newPasswordHash = DigestUtils.md5DigestAsHex(user.getNewPassword().getBytes());
        // 获取当前用户
        SysUser u = new SysUser();
        u.setPassword(newPasswordHash);
        u.setUsername(user.getUsername());
        u.setPhone(user.getPhone());
        u.setStatus(user.getStatus());
        u.setIsAdmin(user.getIsAdmin());
        u.setNickName(user.getNickName());
        u.setSex(user.getSex());
        u.setUserId(user.getUserId());
        if (sysUserService.updateById(u)) {
            return ResultVo.success("修改成功");
        }else {
            return ResultVo.error("修改失败");
        }
    }

    //新增
    @PostMapping
    public ResultVo add(@RequestBody SysUser sysUser) {
        //密码hashMD5加密
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes()));
        if (sysUserService.save(sysUser)) {
            return ResultVo.success("新增成功");
        }else {
            return ResultVo.error("新增失败");
        }
    }

    //编辑
    @PutMapping
    public ResultVo edit(@RequestBody SysUser sysUser) {
        //密码hashMD5加密
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes()));
        if (sysUserService.updateById(sysUser)) {
            return ResultVo.success("编辑成功");
        }else {
            return ResultVo.error("编辑失败");
        }
    }

    //删除
    @DeleteMapping("/{userId}")
    public ResultVo delete(@PathVariable Long userId) {
        if (sysUserService.removeById(userId)) {
            return ResultVo.success("删除成功");
        }else {
            return ResultVo.error("删除失败");
        }
    }

    //查询
    @GetMapping
    public ResultVo getList(PageParam parm) {
        // 创建LambdaQueryWrapper
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(parm.getName())) {
            queryWrapper.like(SysUser::getNickName, parm.getName());
        }
        // 创建分页对象
        Page<SysUser> page = new Page<>(Optional.ofNullable(parm.getCurrentPage()).orElse(1), parm.getPageSize());
        // 执行分页查询
        IPage<SysUser> pageList = sysUserService.page(page, queryWrapper);
        // 返回结果
        return ResultVo.success(pageList);
    }

}
